package com.yukefms.common;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @Description
 * @Author Ping
 * @Date 2021/7/16 0:50
 **/
public class BoundedQueue<T> {

    private ConcurrentLinkedQueue<T> queue ;
    private int bound ;
    /*
    the current index is defined to control the last number of cached data.
     */
    private int curr ;

    public BoundedQueue(final int bound) {
        this.queue = new ConcurrentLinkedQueue<>();
        this.bound = bound;
        this.curr = 0 ;
    }
    public boolean empty() {
        return this.curr == 0 ;
    }

    public void reset() {
        queue.clear();
        this.curr = 0 ;
    }
    public void resetByVal(T t) {
        reset() ;
        add(t) ;
    }

    public T first() {
        if ( ! empty()) {
            this.curr-- ;
            return queue.poll() ;
        }
        return null ;
    }

    public boolean full() {
        return this.curr == bound ;
    }

    public void add(T t) {

        if (full()) {
            this.queue.poll() ;
        } else {
            this.curr++ ;
        }
        this.queue.add(t) ;
    }

}
